const utilities = require('lib/utils'),
    path = require('path'),
    parse = require('co-busboy'),
    fs = require('fs'),
    { dataDir, downloadHost } = require('config');

function waitWriteFinish(stream) {
    return new Promise((resolve, reject) => {
        stream.on('finish', resolve);
    })
}


function* upload(...filesFilter) {
    let fields = parse(this.req, { autoFields: true }),
        field, info = {};

    while (field = yield fields) {
        if (Array.isArray(field)) {
            let [name, value] = field;
            info[name] = value;
        } else {
            let { fieldname, filename, mimeType } = field;
            if (filesFilter.every(k => k != fieldname)) {
                field.resume();
                continue;
            }
            let tmpDir = path.join(dataDir.root, dataDir.tmp);
            let extname = path.extname(filename);
            let saveName = utilities.uuidCode() + extname;
            let streamName = path.join(tmpDir, saveName);
            info[fieldname] = {
                extname,
                saveName,
                savePath: streamName,
                fileName: filename,
                mimeType: mimeType,
                url: downloadHost + streamName
            };
            let stream = fs.createWriteStream(streamName);
            field.pipe(stream);
            yield waitWriteFinish(stream);
        }
    }
    console.log('upload', info)
    return info;
}

module.exports = { upload };